import Banner from "../Banner";
import { ItemData, PlayerData } from "../Datas/Data";
import DroppedItem from "../DroppedItem";
import { Constant, ItemType } from "../Framework/Const/Constant";
import AudioManager from "../Framework/Managers/AudioManager";
import { DataManager } from "../Framework/Managers/DataManager";
import { EventManager, MyEvent } from "../Framework/Managers/EventManager";
import { PoolManager } from "../Framework/Managers/PoolManager";
import { UIManager } from "../Framework/Managers/UIManager";
import NodeUtil from "../Framework/Utils/NodeUtil";
import { ZTool } from "../Framework/Utils/ZTool";
import GameManager from "../GameManager";
import PlayerController from "../PlayerController";
import GamePanel from "./GamePanel";
import GoodsItem from "./GoodsItem";
import InventoryButton from "./InventoryButton";
import ValueBar from "./ValueBar";

const { ccclass, property } = cc._decorator;

export enum InventoryType {
    None = "None",
    Helmet = "头盔",
    Bulletproof = "防弹衣",
    Weapon_0 = "主武器",
    Weapon_1 = "副武器",
    Pistol = "手枪",
    MeleeWeapon = "近战武器",
}

@ccclass
export default class GameInventoryPanel extends cc.Component {
    Helmet: InventoryButton = null;
    Bulletproof: InventoryButton = null;
    Weapon_0: InventoryButton = null;
    Weapon_1: InventoryButton = null;
    Pistol: InventoryButton = null;
    MeleeWeapon: InventoryButton = null;

    buttons: InventoryButton[] = [];

    MoneyLabel: cc.Label = null;

    GoodsTitleLabel: cc.Label = null;
    GoodsContentLabel: cc.Label = null;
    GoodsScrollViewContent: cc.Node = null;
    PlayerGoodsContent: cc.Node = null;
    DetailPanel: cc.Node = null;
    DetailEquipButton: cc.Node = null;
    DetailGoodsContent: cc.Node = null;
    DetailGoodsLabel: cc.Label = null;
    DetailUseButton: cc.Node = null;
    DetailTakeButton: cc.Node = null;
    GoodsSearchLabel: cc.Node = null;
    ValuesContent: cc.Node = null;

    PlayerBackpackItems: GoodsItem[] = [];
    GoodsItems: GoodsItem[] = [];
    DetailGoodsItem: GoodsItem = null;

    ItemDatas: ItemData[] = [];
    SelectItemData: ItemData = null;
    valueBars: cc.Node[] = [];

    protected onLoad(): void {
        this.Helmet = NodeUtil.GetComponent("Helmet", this.node, InventoryButton);
        this.Bulletproof = NodeUtil.GetComponent("Bulletproof", this.node, InventoryButton);
        this.Weapon_0 = NodeUtil.GetComponent("Weapon_0", this.node, InventoryButton);
        this.Weapon_1 = NodeUtil.GetComponent("Weapon_1", this.node, InventoryButton);
        this.Pistol = NodeUtil.GetComponent("Pistol", this.node, InventoryButton);
        this.MeleeWeapon = NodeUtil.GetComponent("MeleeWeapon", this.node, InventoryButton);
        this.MoneyLabel = NodeUtil.GetComponent("MoneyLabel", this.node, cc.Label);

        this.buttons.push(this.Helmet);
        this.buttons.push(this.Bulletproof);
        this.buttons.push(this.Weapon_0);
        this.buttons.push(this.Weapon_1);
        this.buttons.push(this.Pistol);
        this.buttons.push(this.MeleeWeapon);

        this.GoodsTitleLabel = NodeUtil.GetComponent("GoodsTitleLabel", this.node, cc.Label);
        this.GoodsContentLabel = NodeUtil.GetComponent("GoodsContentLabel", this.node, cc.Label);
        this.GoodsScrollViewContent = NodeUtil.GetNode("GoodsScrollViewContent", this.node);
        this.DetailPanel = NodeUtil.GetNode("DetailPanel", this.node);
        this.DetailEquipButton = NodeUtil.GetNode("DetailEquipButton", this.node);
        this.DetailGoodsContent = NodeUtil.GetNode("DetailGoodsContent", this.node);
        this.DetailGoodsLabel = NodeUtil.GetComponent("DetailGoodsLabel", this.node, cc.Label);
        this.DetailUseButton = NodeUtil.GetNode("DetailUseButton", this.node);
        this.DetailTakeButton = NodeUtil.GetNode("DetailTakeButton", this.node);
        this.PlayerGoodsContent = NodeUtil.GetNode("PlayerGoodsContent", this.node);
        this.GoodsSearchLabel = NodeUtil.GetNode("GoodsSearchLabel", this.node);
        this.ValuesContent = NodeUtil.GetNode("ValuesContent", this.node);
    }

    Show(title: string, itemDatas: ItemData[], searchTime: number = 2) {
        this.Helmet.Set(InventoryType.Helmet);
        this.Bulletproof.Set(InventoryType.Bulletproof);
        this.Weapon_0.Set(InventoryType.Weapon_0);
        this.Weapon_1.Set(InventoryType.Weapon_1);
        this.Pistol.Set(InventoryType.Pistol);
        this.MeleeWeapon.Set(InventoryType.MeleeWeapon);
        this.GoodsSearchLabel.active = true;
        this.GoodsItems.forEach((e) => PoolManager.PutNode(e.node));

        this.GoodsSearchLabel.active = itemDatas && itemDatas.length > 0;

        this.scheduleOnce(() => {
            this.GoodsSearchLabel.active = false;
            this.RefreshGoodsItem();
        }, searchTime);

        if (Banner.NeedShowMoreAd) {
            this.scheduleOnce(() => {
                Banner.Instance.ShowCustomAd();
            }, searchTime + 1);
        }

        this.SelectItemData = null;
        this.ItemDatas = itemDatas;
        this.GoodsTitleLabel.string = `${title}`;
        this.RefreshMoney();
        this.RefreshInventoryButtons();
        this.RefreshBackpackGoodsItem();
        this.ShowValues();
    }

    ShowDetailPanel(active: boolean, isEquippedItem: boolean = false) {
        this.DetailPanel.active = active;

        if (active) {
            if (this.DetailGoodsItem) PoolManager.PutNode(this.DetailGoodsItem.node);
            PoolManager.GetNode("Prefabs/UI/GoodsItem", this.DetailGoodsContent).then((node) => {
                let goods = node.getComponent(GoodsItem);
                goods.InitSimple(this.SelectItemData);
                this.DetailGoodsItem = goods;
                this.DetailGoodsLabel.string = `${this.SelectItemData.Name}`;
            });

            let inPlayerGoods = DataManager.PlayerData.BackpackItems.indexOf(this.SelectItemData) != -1;
            this.DetailUseButton.active = (!isEquippedItem || inPlayerGoods) && !(this.SelectItemData.Type == ItemType[ItemType.战利品]);
            this.DetailTakeButton.active = this.ItemDatas.indexOf(this.SelectItemData) != -1;
        } else {
            this.SelectItemData = null;
        }

        this.ShowValues(this.SelectItemData != null && isEquippedItem, this.SelectItemData);
    }

    ShowValues(active: boolean = false, data = null) {
        this.valueBars.forEach(e => PoolManager.PutNode(e));
        this.ValuesContent.active = active;

        if (active && !(this.ItemDatas && this.ItemDatas.length > 0)) {
            let hasValues = false;
            let type = ItemType[`${data.Type}`];
            if (ItemData.IsGun(type)) {
                hasValues = true;
                PoolManager.GetNode("Prefabs/UI/ValueBar", this.ValuesContent).then((node: cc.Node) => {
                    node.getComponent(ValueBar).Init(data.Damage / 90, `伤害`);
                    this.valueBars.push(node);
                });
                PoolManager.GetNode("Prefabs/UI/ValueBar", this.ValuesContent).then((node: cc.Node) => {
                    node.getComponent(ValueBar).Init((1.5 - data.FireRate) / 1.5, `射速`);
                    this.valueBars.push(node);
                });
                PoolManager.GetNode("Prefabs/UI/ValueBar", this.ValuesContent).then((node: cc.Node) => {
                    node.getComponent(ValueBar).Init(data.Recoil / 0.5, `后坐力`);
                    this.valueBars.push(node);
                });
            }

            if (ItemData.IsEquip(type)) {
                hasValues = true;

                PoolManager.GetNode("Prefabs/UI/ValueBar", this.ValuesContent).then((node: cc.Node) => {
                    node.getComponent(ValueBar).Init(data.Lv / 5, `防护等级`);
                    this.valueBars.push(node);
                });
                PoolManager.GetNode("Prefabs/UI/ValueBar", this.ValuesContent).then((node: cc.Node) => {
                    node.getComponent(ValueBar).Init(data.Durability / 100, `耐久度`);
                    this.valueBars.push(node);
                });
            }

            if (ItemData.IsMedicine(type)) {
                hasValues = true;

                PoolManager.GetNode("Prefabs/UI/ValueBar", this.ValuesContent).then((node: cc.Node) => {
                    node.getComponent(ValueBar).Init(data.HP / 500, `血量`);
                    this.valueBars.push(node);
                });
                PoolManager.GetNode("Prefabs/UI/ValueBar", this.ValuesContent).then((node: cc.Node) => {
                    node.getComponent(ValueBar).Init((6 - data.Time) / 6, `速度`);
                    this.valueBars.push(node);
                });
            }

        }
    }

    RefreshGoodsItem() {
        this.GoodsItems.forEach((e) => PoolManager.PutNode(e.node));

        for (let i = 0; i < this.ItemDatas.length; i++) {
            const data = this.ItemDatas[i];
            PoolManager.GetNode("Prefabs/UI/GoodsItem", this.GoodsScrollViewContent).then((node) => {
                let goods = node.getComponent(GoodsItem);
                goods.Init(data, this.OnGoodsItemCallback.bind(this));
                this.GoodsItems.push(goods);
            });
        }
    }

    RefreshInventoryButtons() {
        this.buttons.forEach(e => e.Refresh());
    }

    RefreshBackpackGoodsItem() {
        this.PlayerBackpackItems.forEach((e) => PoolManager.PutNode(e.node));
        for (let i = 0; i < PlayerData.MaxBackpackItems; i++) {
            const data = DataManager.PlayerData.BackpackItems[i];
            PoolManager.GetNode("Prefabs/UI/GoodsItem", this.PlayerGoodsContent).then((node) => {
                let goods = node.getComponent(GoodsItem);
                if (data) {
                    goods.Init(data, this.OnGoodsItemCallback.bind(this));
                } else {
                    goods.InitBlank();
                }
                this.PlayerBackpackItems.push(goods);
            });
        }
    }

    OnGoodsItemCallback(data: ItemData) {
        this.GoodsItems.forEach((e) => e.SetSelected(data));
        this.PlayerBackpackItems.forEach((e) => e.SetSelected(data));
        this.SelectItemData = data;
        this.ShowDetailPanel(true);
    }

    InventoryType: InventoryType;

    OnButtonClick(event: cc.Event) {
        AudioManager.PlayAudio(Constant.Audio.ButtonClick);
        this.buttons.forEach(e => e.RefreshSelected(InventoryType[event.target.name]));

        switch (event.target.name) {
            case "Helmet"://头盔
                if (!DataManager.PlayerData.Helmet) {
                    UIManager.Instance.ShowPanel(Constant.Panel.ShopPanel, [ItemType.头盔]);
                } else {
                    this.SelectItemData = DataManager.PlayerData.Helmet;
                    this.ShowDetailPanel(true, true);
                }
                break;
            case "Bulletproof"://防弹衣
                if (!DataManager.PlayerData.Bulletproof) {
                    UIManager.Instance.ShowPanel(Constant.Panel.ShopPanel, [ItemType.防弹衣]);
                } else {
                    this.SelectItemData = DataManager.PlayerData.Bulletproof;
                    this.ShowDetailPanel(true, true);
                }
                break;
            case "Weapon_0"://主武器
                if (!DataManager.PlayerData.Weapon_0) {
                    UIManager.Instance.ShowPanel(Constant.Panel.ShopPanel, [ItemType.突击步枪]);
                } else {
                    this.SelectItemData = DataManager.PlayerData.Weapon_0;
                    this.ShowDetailPanel(true, true);
                }
                break;
            case "Weapon_1"://副武器
                if (!DataManager.PlayerData.Weapon_1) {
                    UIManager.Instance.ShowPanel(Constant.Panel.ShopPanel, [ItemType.射手步枪]);
                } else {
                    this.SelectItemData = DataManager.PlayerData.Weapon_1;
                    this.ShowDetailPanel(true, true);
                }
                break;
            case "Pistol"://手枪
                if (!DataManager.PlayerData.Pistol) {
                    UIManager.Instance.ShowPanel(Constant.Panel.ShopPanel, [ItemType.手枪]);
                } else {
                    this.SelectItemData = DataManager.PlayerData.Pistol;
                    this.ShowDetailPanel(true, true);
                }
                break;
            case "MeleeWeapon"://近战武器
                this.SelectItemData = DataManager.PlayerData.MeleeWeapon;
                this.ShowDetailPanel(true, true);
                break;
            case "ReturnButton":
                UIManager.Instance.HidePanel(Constant.Panel.GameInventoryPanel);
                break;
            case "DetailUseButton":
                if (this.SelectItemData.Type == ItemType[ItemType.子弹]) {
                    if (DataManager.PlayerData.Weapon_0 && (DataManager.PlayerData.Weapon_0 as any).Desc == this.SelectItemData.Name) {
                        (DataManager.PlayerData.Weapon_0 as any).BulletCount += this.SelectItemData.Count;
                        AudioManager.PlayAudio(Constant.Audio.Equip);
                        DataManager.RemoveItemFromBackpack(this.SelectItemData);
                        this.ShowDetailPanel(false);
                    }
                    else if (DataManager.PlayerData.Weapon_1 && (DataManager.PlayerData.Weapon_1 as any).Desc == this.SelectItemData.Name) {
                        (DataManager.PlayerData.Weapon_1 as any).BulletCount += this.SelectItemData.Count;
                        AudioManager.PlayAudio(Constant.Audio.Equip);
                        DataManager.RemoveItemFromBackpack(this.SelectItemData);
                        this.ShowDetailPanel(false);
                    }
                    else if (DataManager.PlayerData.Pistol && (DataManager.PlayerData.Pistol as any).Desc == this.SelectItemData.Name) {
                        (DataManager.PlayerData.Pistol as any).BulletCount += this.SelectItemData.Count;
                        AudioManager.PlayAudio(Constant.Audio.Equip);
                        DataManager.RemoveItemFromBackpack(this.SelectItemData);
                        this.ShowDetailPanel(false);
                    } else {
                        UIManager.ShowTip("没有合适的枪械");
                    }
                } else if (ItemData.IsMainGun(ItemType[this.SelectItemData.Type])) {
                    //装备 0 或者 1
                    if (DataManager.AddEquippedItem(InventoryType.Weapon_0, this.SelectItemData) || DataManager.AddEquippedItem(InventoryType.Weapon_1, this.SelectItemData)) {
                        this.RefreshGoodsItem();
                        AudioManager.PlayAudio(Constant.Audio.Equip);
                        DataManager.RemoveItemFromBackpack(this.SelectItemData);
                    } else {
                        UIManager.ShowTip("装备已满");
                    }
                } else if (ItemType[this.SelectItemData.Type] == ItemType.手枪) {
                    if (DataManager.AddEquippedItem(InventoryType.Pistol, this.SelectItemData)) {
                        this.RefreshGoodsItem();
                        AudioManager.PlayAudio(Constant.Audio.Equip);
                        DataManager.RemoveItemFromBackpack(this.SelectItemData);
                    } else {
                        UIManager.ShowTip("已有装备");
                    }
                } else if (ItemType[this.SelectItemData.Type] == ItemType.头盔) {
                    if (DataManager.AddEquippedItem(InventoryType.Helmet, this.SelectItemData)) {
                        this.RefreshGoodsItem();
                        AudioManager.PlayAudio(Constant.Audio.Equip);
                        DataManager.RemoveItemFromBackpack(this.SelectItemData);
                    } else {
                        UIManager.ShowTip("已有装备");
                    }
                } else if (ItemType[this.SelectItemData.Type] == ItemType.防弹衣) {
                    if (DataManager.AddEquippedItem(InventoryType.Bulletproof, this.SelectItemData)) {
                        this.RefreshGoodsItem();
                        AudioManager.PlayAudio(Constant.Audio.Equip);
                        DataManager.RemoveItemFromBackpack(this.SelectItemData);
                    } else {
                        UIManager.ShowTip("已有装备");
                    }
                }
                else if (ItemType[this.SelectItemData.Type] == ItemType.药品) {
                    if (GameManager.Instance.playerCtrl.HP < PlayerController.MAXHP) {
                        UIManager.Instance.HidePanel(Constant.Panel.GameInventoryPanel);
                        GamePanel.Instance.ShowUseItem(true, this.SelectItemData, (HP) => {
                            GameManager.Instance.playerCtrl.HP += HP;
                            DataManager.RemoveItemFromBackpack(this.SelectItemData);
                            this.RefreshBackpackGoodsItem();
                        });
                    } else {
                        UIManager.ShowTip("血量已满");
                    }
                }
                this.ShowDetailPanel(false);
                EventManager.Scene.emit(MyEvent.RefreshEquip);
                break;
            case "DetailDetailButton":
                UIManager.Instance.ShowPanel(Constant.Panel.ItemDetailPanel, [this.SelectItemData]);
                break;
            case "DetailDropButton":
                if (this.SelectItemData) {
                    const itemData = this.SelectItemData;
                    if (itemData.Type == ItemType[ItemType.近战武器]) return;
                    if (DataManager.RemovePlayerItem(this.SelectItemData) || DataManager.RemovePlayerEquippedItem(this.SelectItemData) || DataManager.RemoveItemFromBackpack(this.SelectItemData)) {
                        PoolManager.GetNode("Prefabs/DroppedItem", GameManager.Instance.ItemsNd).then(node => {
                            NodeUtil.SetWorldPosition(node, NodeUtil.GetWorldPosition(GameManager.Instance.player));
                            node.getComponent(DroppedItem).Init(itemData);
                        });
                    }
                    AudioManager.PlayAudio(Constant.Audio.Unequip);
                    this.RefreshGoodsItem();
                    this.ShowDetailPanel(false);

                    EventManager.Scene.emit(MyEvent.RefreshEquip);
                }
                break;
            case "DetailCloseButton":
                this.ShowDetailPanel(false);
                break;
            case "DetailTakeButton":
                if (DataManager.AddItemToBackpack(this.SelectItemData)) {
                    ZTool.RemoveItemFromArray(this.ItemDatas, this.SelectItemData);
                    this.RefreshBackpackGoodsItem();
                    this.RefreshGoodsItem();
                } else {
                    UIManager.ShowTip("背包已满");
                }
                this.ShowDetailPanel(false);
                break;
        }

        this.RefreshInventoryButtons();
    }

    RefreshMoney() {
        this.MoneyLabel.string = `${DataManager.Money}`;
    }

    protected onEnable(): void {
        EventManager.on(MyEvent.RefreshMoney, this.RefreshMoney, this);
        EventManager.on(MyEvent.RefreshGoodsItem, this.RefreshGoodsItem, this);
        EventManager.on(MyEvent.RefreshBackpackGoodsItem, this.RefreshBackpackGoodsItem, this);
        EventManager.on(MyEvent.RefreshInventoryButtons, this.RefreshInventoryButtons, this);
    }

    protected onDisable(): void {
        EventManager.off(MyEvent.RefreshMoney, this.RefreshMoney, this);
        EventManager.off(MyEvent.RefreshGoodsItem, this.RefreshGoodsItem, this);
        EventManager.off(MyEvent.RefreshBackpackGoodsItem, this.RefreshBackpackGoodsItem, this);
        EventManager.off(MyEvent.RefreshInventoryButtons, this.RefreshInventoryButtons, this);
    }
}
